package com.example.user.myfirstapp.activity;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.example.user.myfirstapp.R;
import com.example.user.myfirstapp.sqlitedb.DbHelper;
import com.example.user.myfirstapp.sqlitedb.SqliteDb;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

public class SearchActivity extends Activity implements View.OnClickListener{
    private TextView tv_search_cancel,tv_logcount;
    private ListView lv_searchlog;
    private EditText et_search;
    private Button bt_clearlog;
    private ArrayList<HashMap<String, Object>> listItem;
    private SimpleAdapter listItemAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        tv_logcount=(TextView)findViewById(R.id.tv_logcount);
        tv_search_cancel=(TextView)findViewById(R.id.tv_search_cancel);
        tv_search_cancel.setOnClickListener(this);
        lv_searchlog=(ListView)findViewById(R.id.lv_searchlog);
        bt_clearlog=(Button)findViewById(R.id.bt_clearlog);
        bt_clearlog.setOnClickListener(this);
        et_search=(EditText)findViewById(R.id.et_search);
        et_search.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //是否是回车键
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    //隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //搜索
                    search();
                }
                return false;
            }
        });

        //加载历史记录
        loadHistoryLog();
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_search_cancel:
                finish();
                break;
            case R.id.bt_clearlog:
                clearLogData();
                break;
            default:
                break;
        }
    }

    private void search(){
        try {
            String searchContent = et_search.getText().toString().trim();
            if (!TextUtils.isEmpty(searchContent)) {
                //把关键词写入手机本地数据库
                insertLog(searchContent);
                //跳转到搜索列表
                goToList(searchContent);
            }
        }
        catch (Exception e){
        }
    }

    //加载历史记录
    private void loadHistoryLog(){
        try {
            listItem = new ArrayList<HashMap<String, Object>>();
            SqliteDb db = new SqliteDb(this);
            SQLiteDatabase dbread = db.getReadableDatabase();
            Cursor c = dbread.query("searchLog", null, null, null, null, null, "logtime desc", null);
            int count = c.getCount();
            if (count > 0) {
                tv_logcount.setText("搜索历史 （" + count + "条记录）");

                while (c.moveToNext()) {
                    String name = c.getString(c.getColumnIndex("logname"));
                    //String timestr = c.getString(c.getColumnIndex("logtime"));
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put("logName", name);
                    listItem.add(map);
                }
                listItemAdapter = new SimpleAdapter(
                        this,
                        listItem, //数据源
                        R.layout.searchlog_item, //ListItem的XML实现
                        new String[]{"logName"},//动态数组与listItem对应的子项
                        new int[]{R.id.searchlog_itemTitle}
                );
                //添加并且显示
                lv_searchlog.setAdapter(listItemAdapter);
                lv_searchlog.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (id == -1)
                            return;
                        int realPosition = (int) id;
                        ListView lv = (ListView) parent;
                        HashMap<String, Object> map = (HashMap<String, Object>) lv.getItemAtPosition(realPosition);
                        String logName = map.get("logName").toString();
                        goToList(logName);
                    }
                });
            }
            else {
                bt_clearlog.setVisibility(View.GONE);
            }
        }catch (Exception e){

        }
    }

    private void insertLog(String searchContent){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String strTime = formatter.format(curDate);
        SqliteDb db=new SqliteDb(this);
        SQLiteDatabase dbwriter =db.getWritableDatabase();
        ContentValues cv=new ContentValues();
        cv.put("logname",searchContent);
        cv.put("logtime",strTime);
        dbwriter.insert("searchLog",null,cv);
        dbwriter.close();
    }

    private void goToList(String searchContent){
        Intent intent =new Intent(this,SearchListActivity.class);
        Bundle bundle=new Bundle();
        bundle.putString("serachKey", searchContent);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void clearLogData(){
        try {
            DbHelper dbhelper = new DbHelper(this);
            dbhelper.clearTable("searchLog");//删除搜索记录表
            tv_logcount.setText("搜索历史 （0条记录）");
            lv_searchlog.setAdapter(null);
            bt_clearlog.setVisibility(View.GONE);
        }catch (Exception e){

        }
    }
}
